<?php

namespace App\Service\Common;

use App\Service\WaiMai\WaiMaiAnalysisService;
use IcyData\Heatmap;
use IcyData\Heatmap\Colours;
use Illuminate\Support\Str;

class HeatMapService
{
    public static function calculateXYInImage(array $center, int $imageWidth, int $imageHeight, array $coordinate)
    {
        // 计算图片左上角点的经纬度坐标
        $leftTop = ['lng' => $center['lng'] - ($imageWidth / 2) * 0.00002171972656, 'lat' => $center['lat'] + ($imageHeight / 2) * 0.0000182109375];
        // 计算给定坐标与图片左上角点的距离（单位：度）
        $distance = ['lng' => $coordinate['lng'] - $leftTop['lng'], 'lat' => $leftTop['lat'] - $coordinate['lat']];
        // 计算距离对应的像素值
        $pixelX = $distance['lng'] / 0.00002131054688;
        $pixelY = $distance['lat'] / 0.0000182109375;
        // 坐标原点为图片左上角点，需要转换坐标系
        $x = $pixelX;
        $y = $imageHeight - $pixelY;
        return ['x' => round($x), 'y' => round($y)];
    }


    /**
     * @throws \Exception
     */
    public static function makeHeatMap($path, $lng, $lat): string
    {
        $paletteImage = imagecreatefrompng($path);
        $truecolorImage = imagecreatetruecolor(1024, 1024); // 创建一个真彩色图像资源
        imagecopy($truecolorImage, $paletteImage, 0, 0, 0, 0, 1024, 1024); // 将索引色图像资源复制到真彩色图像资源中
        imagedestroy($paletteImage); // 释放索引色图像资源
        $dir = sys_get_temp_dir() . '/heatMap/';
        if (!is_dir($dir)) {
            mkdir($dir);
        }
        $backgroundImage = $dir . Str::random() . '.png';
        $cacheFile       = $dir . 'cachegradient.png';
        imagepng($truecolorImage, $backgroundImage);
        imagedestroy($truecolorImage); // 释放索引色图像资源
        $heatmap = new Heatmap([
            'backgroundImg'   => $backgroundImage,
            'radius'          => 15,
            'gradientColours' => [
                Colours::BLUE,
                Colours::GREEN,
                Colours::YELLOW,
                Colours::RED,
                Colours::RED
            ],
            'cacheDir'        => $dir
        ]);
        // 外卖预估数据
        $takeOutData = (new WaiMaiAnalysisService())
            ->setLngLat($lng, $lat, 1.5);

        $arr = [];
        $takeOutData->getNearByShop()->each(function ($item) use ($lng, $lat, &$arr) {
            $coordinate = self::calculateXYInImage(['lng' => $lng, 'lat' => $lat], 1024, 1024, ['lng' => $item['lng'], 'lat' => $item['lat']]);
            if ($coordinate['x'] > 1024 || $coordinate['y'] > 1024 || $coordinate['x'] <= 0 || $coordinate['y'] <= 0) {
                return;
            }
            $xi                   = (int)$coordinate['x'];
            $yi                   = (int)$coordinate['y'];
            $arr[$xi . 'x' . $yi] = [
                'x'     => $xi,
                'y'     => $yi,
                'count' => $item['orderNum'] ?: 1
            ];
        });
        foreach ($arr as $value) {
            $heatmap->addPoint($value['x'], $value['y']);
        }
        $file = $dir . Str::random() . '.png';
        $heatmap->save($file);
        @unlink($backgroundImage);
        @unlink($cacheFile);
        return $file;
    }
}
